<template>
    <el-form class="sign-form" ref="signInRef" :model="form" :rules="rules">
        <el-form-item class="sign-form-item" prop="name">
            <el-input class="sign-input" placeholder="用户名" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item class="sign-form-item" prop="password">
            <el-input class="sign-input" placeholder="密码" v-model="form.password"></el-input>
        </el-form-item>
    </el-form>
    <div class="login-options">
        <el-checkbox>记住我</el-checkbox>
        <router-link class="link" to="/reset-pwd">忘记密码</router-link>
    </div>
    <div class="submit-warp">
        <el-button class="submit" type="primary"
            :loading="loading" @click="submit">
            登 录
        </el-button>
    </div>
</template>

<script lang="ts" setup>
import { login } from '@/apis/user'
import type { LoginData, LoginRes } from '@/apis/user/types'
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import useStore from '@/store'
const { user } = useStore()

const signInRef = ref<FormInstance>()
const form = reactive<LoginData>({
    name: '',
    password: '',
    keep: false
})

// 验证规则
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
})

const loading = ref<boolean>(false)

// 登录提交，成功后返回上一级
const router = useRouter()
const submit = () => {
    loading.value = true
    if(!signInRef) return
    signInRef.value?.validate(async (valid) => {
        if(valid) {
            try {
                const res: LoginRes = await login(form)
                user.setToken(res.token)
                // router.go(-1)
                router.push('/')
                loading.value = false
            } catch(e) {
                loading.value = false                
            }
        }
    })
}

// 重置表单

</script>

<style lang="less" scoped>
@import './sign.less';
.login-options {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .link {
        font-size: var(font-size-medium);
    }
}
</style>